package com.xingfudazi.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xingfudazi.app.domain.AppMessage;
import com.xingfudazi.app.enums.MessageEnum;
import com.xingfudazi.app.mapper.AppMessageMapper;
import com.xingfudazi.app.service.IAppMessageService;
import com.xingfudazi.common.utils.SecurityUtils;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author YuJiaMing
 * date 2024年06月22日 23:04
 */
@Service
public class AppMessageServiceImpl implements IAppMessageService {

    @Autowired
    private AppMessageMapper appMessageMapper;

    @Override
    public List<AppMessage> turn(Integer pageSize, Long lastId, MessageEnum type) {
        LambdaQueryWrapper<AppMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(AppMessage::getCreateTime);
        wrapper.eq(AppMessage::getReceiverId, SecurityUtils.getUserId());
        if (lastId != null) {
            wrapper.lt(AppMessage::getId, lastId);
        }

        if (type != null) {
            wrapper.eq(AppMessage::getType, type.name());
        }

        PageHelper.startPage(1, pageSize);
        return this.appMessageMapper.selectList(wrapper);
    }

    @Override
    public void add(AppMessage appMessage) {
        this.appMessageMapper.insert(appMessage);
    }

    @Override
    public void read(Long id) {
        LambdaQueryWrapper<AppMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppMessage::getReceiverId, SecurityUtils.getUserId());
        wrapper.eq(id != null, AppMessage::getId, id);

        AppMessage appMessage = new AppMessage();
        appMessage.setReadTime(LocalDateTime.now());

        this.appMessageMapper.update(appMessage, wrapper);
    }


    @Override
    public Integer getUnReadNum() {
        LambdaQueryWrapper<AppMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppMessage::getReceiverId, SecurityUtils.getUserId());
        wrapper.isNull(AppMessage::getReadTime);
        return this.appMessageMapper.selectCount(wrapper);
    }
}
